import aiortc
from aiortc import RTCPeerConnection, RTCSessionDescription, VideoStreamTrack, AudioStreamTrack, MediaStreamTrack
from aiortc.contrib.media import MediaPlayer, MediaRelay
from aiortc.rtcrtpsender import RTCRtpSender

import aiohttp
from aiohttp import TCPConnector
import asyncio
import random
import json
import time
import sys
# import ssl
# import cv2

# read from the camera using ffmpeg
# class CustomVideoStreamTrack(VideoStreamTrack):
#     def __init__(self):
#         super().__init__()
#     async def recv(self):
        

ip = "39.106.77.250"
stream_url = "webrtc://{}:1990/live/livestream1?schema=https".format(ip)
api = "https://{}:1990/rtc/v1/publish/".format(ip)

print("Stream URL:", stream_url)
print("API URL:", api)

async def main():
    print("Starting main function")

    if len(sys.argv) == 3:
        # 获取分辨率参数
        resolution = sys.argv[1]
        framerate = sys.argv[2]
        print(f"Processing with resolution: {resolution}")
    else:
        resolution = "640x360"
        framerate = "30"
        print("No resolution provided, using default.")

    # 构建选项字典
    options = {
        "framerate": framerate,
        "video_size": resolution,
        # "limit_size": "off",
        "input_format": "mjpeg"  # 设置为 MJPG 格式
    }


    # options = {
    #     "framerate": "15",
    #     "video_size": "640x360",
    #     "limit_size": "off",
        
    # }

    # options = {
    #     "framerate": "15",
    #     "video_size": "1280x720",
    #     "limit_size": "off",
        
    # }
    
    print("Initializing MediaPlayer")
    webcam = MediaPlayer("/dev/video0", format="v4l2", options=options)
    # webcam = MediaPlayer("/dev/video0", format="", options=options)
    relay = MediaRelay()
    returned_relays = relay.subscribe(webcam.video)
    
    print("Creating RTCPeerConnection")
    pc = RTCPeerConnection()
    
    @pc.on("connectionstatechange")
    async def on_connectionstatechange():
        print("Connection state:", pc.connectionState)
        if pc.connectionState == "failed":
            await pc.close()
    
    print("Adding video track")
    video_sender = pc.addTrack(returned_relays)
            
    force_codec = "video/H264"
    kind = "video"
    codecs = RTCRtpSender.getCapabilities(kind).codecs
    transceiver = next(t for t in pc.getTransceivers() if t.sender == video_sender)
    transceiver.setCodecPreferences(
        [c for c in codecs if c.mimeType == force_codec]
    )
    
    print("Creating and setting local description")
    offer = await pc.createOffer()
    await pc.setLocalDescription(offer)
    
    global stream_url, api
    print("URL: ", stream_url)
    data = {
        "api": api,
        "tid": hex(int(time.time()) * random.randint(8932891839, 312371231928731))[2:9],
        "streamurl": stream_url,
        "clentip": None,
        "sdp": offer.sdp
    }
    
    print("Sending POST request to API")
    print(data)
    response = None
    async with aiohttp.ClientSession() as session:
        async with session.post(api, data=json.dumps(data), ssl=False) as resp:
            response = await resp.json()
    
    print("Response received:", response)
    
    await pc.setRemoteDescription(RTCSessionDescription(
        sdp=response["sdp"], type="answer"
    ))
    
    
if __name__ == "__main__":
    print("Running main function")
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.run_forever()     
